'''
Created on 04/12/2009

@author: eh01
'''
from runtime.task import Task
from datastore.resource import Resource
from datastore.database import DataStore, NotFoundException
import logging

class UpdateManagerTask(Task):
    
    def __init__(self, ds, spaces, task_uri, task_def_rs):
        # <purpose>
        #
        # Parameters:
        #     ds : datastore.database.DataStore
        #     spaces : runtime.spaces.Spaces - Reference to spaces
        #     task_uri : String - the uri for this task. The root uri will most
        #                likely be the 'binding' uri for this task.
        #     task_def_rs : datastore.resource.Resource - Task definition resource.
        #
        
        Task.__init__(self, ds, spaces, task_uri, task_def_rs)
        
        self.logger = logging.getLogger('yarra.services.updatemanagertask.UpdateManagerTask')
        self.logger.log(logging.DEBUG, "ds (%s), spaces (%s), task_uri (%s), task_def_rs (%s)" % (ds, spaces, task_uri, task_def_rs.pretty_print()))
    
    def cb_start(self, method, uri, res, result, context, **kwargs):
        uri_package = context.uri('package:')
        context.watch_all(['put'], uri_package, 'cb_install_package')
        

    def cb_install_package(self, method, uri, new_uri, result, context, **kwargs):
        '''
        Downloads the package and prepares it for installation. The resource placed in Spaces should
        have a url attribute, which is the url(String) of the package location. 
        '''
        uri_httpclient = context.uri('httpclient:')
        uri_package = context.uri('package:')
        uri_datastore = context.uri('datastore:')
        uri_local = context.uri('local:')
        package_name = new_uri.split()[-1]
        # get package resource
        res = context.get(new_uri)
        request_resource = Resource()
        request_resource.url = res.url
        # TODO: need code here to check if it is a HTTP request or not and set the http_method appropriately
        request_resource.http_method = 'GET'
        request_resource.data = None
        self.logger.log(logging.DEBUG, "Resource url %s" % (request_resource.url))
        request_uri = context.put(uri_httpclient.request.collection(True), request_resource)
        response_resource = context.get_wait(request_uri.response)
        self.logger.log(logging.DEBUG, "Response code %s" % (response_resource.code))
        if response_resource.code and response_resource.code != 200:
            self.logger.log(logging.ERROR, "Error retrieving package at %s" % (request_resource.url))
        # set the encoded binary contents
        res.bin = response_resource.content
        res.set_metadata(uri_datastore.resource.type, uri_package.type.package)
        res.set_metadata(uri_package.status, 'to_install')
        res.set_metadata(uri_package.packagename, package_name)
        self.logger.log(logging.DEBUG, "Storing package in Datastore")
        ds = DataStore(context.spaces.ns)
        try:
            resources = ds.find(res.get_all_metadata())
            ds.delete(resources)
            ds.put(res)
        except NotFoundException:
            ds.put(res)
        self.logger.log(logging.DEBUG, "Restart %s" % (uri_local.restart.full_uri))
        context.get(uri_local.restart)